<h1>Go Details 101</h1>

<div>
Index:

<ul class="summaries" id="details.html">
<li>
	Code package related details:
	<ul class="index">
	<li>
		<a class="index" href="#import-package-multiple-times">A package can be imported more than once in a source file.</a>
	</li>
	<li>
		<a class="index" href="#force-import-path">The comment <code>// import "x.y.z/mypkg"</code> following <code>package mypkg</code> is meaningful for the standard Go compiler.</a>
	</li>
	</ul>
</li>
<li>
	Control flow related details:
	<ul class="index">
	<li>
		<a class="index" href="#default-branch-position">The <code>default</code> branch in <code>switch</code> and <code>select</code> blocks can be put before all <code>case</code> branches, after all <code>case</code> branches, or between <code>case</code> branches.</a>
	</li>
	<li>
		<a class="index" href="#constant-case-expressions">The numeric constant case expressions in a <code>switch</code> block can't be duplicate, but boolean ones can.</a>
	</li>
	<li>
		<a class="index" href="#switch-expressions-are-typed">The switch expressions in <code>switch</code> block are always evaluated to typed values.</a>
	</li>
	<li>
		<a class="index" href="#default-switch-expression-value">The default switch expression of a <code>switch</code> block is a typed value <code>true</code> of the predeclared type <code>bool</code>.</a>
	</li>
	<li>
		<a class="index" href="#open-brace-on-the-next-line">Sometimes, the open brace <code>{</code> of an explicit code block can be put on the next line.</a>
	</li>
	<li>
		<a class="index" href="#some-case-branch-blocks-must-be-explicit">Some <code>case</code> branch blocks must be explicit.</a>
	</li>
	<li>
		<a class="index" href="#defer-modify-results">Nested deferred function calls can modify return result values of nesting functions.</a>
	</li>
	<li>
		<a class="index" href="#no-op-recover-calls">Some <code>recover</code> calls may be NoOps.</a>
	</li>
	<li>
		<a class="index" href="#os-exit-runtime-goexit">Exit a program with a <code>os.Exit</code> function call and exit a goroutine with a <code>runtime.Goexit</code> function call</a>.
	</li>
	</ul>
</li>
<li>
	Operator related details:
	<ul class="index">
	<li>
		<a class="index" href="#some-operator-precedence">The precedence of the increment operator <code>++</code> and the decrement <code>--</code> is lower than the dereference operator <code>*</code> and the address-taken operator <code>&amp;</code>, which are lower than the property selection operator <code>.</code> in selectors.</a>
	</li>
	<li>
		<a class="index" href="#type-deduction-in-bit-shift">The type deduction rule for the left untyped operand of a bit-shift operation depends on whether or not the right operand is a constant.</a>
	</li>
	</ul>
</li>
<li>
	Pointer related details:
	<ul class="index">
	<li>
		<a class="index" href="#conversion-of-pointers-with-different-underlying-types">Values of two pointer types with different underlying types can be converted to each other if the base types of their underlying types share the same underlying type.</a>
	</li>
	<li>
		<a class="index" href="#addresses-of-zeor-sized-values">Addresses of different zero-sized values may be equal, or not.</a>
	</li>
	<li>
		<a class="index" href="#self-based-pointer-type">The base type of a pointer type may be the pointer type itself.</a>
	</li>
	<li>
		<a class="index" href="#pointer-selector-shorthands">A detail about selector shorthands.</a>
	</li>
	</ul>
</li>
<li>
	Container related details:
	<ul class="index">
	<li>
		<a class="index" href="#composite-literal-simplification">Sometimes, nested composite literals can be simplified.</a>
	</li>
	<li>
		<a class="index" href="#use-pointer-as-array">In some scenarios, it is ok to use array pointers as arrays.</a>
	</li>
	<li>
		<a class="index" href="#nil-map-element-retrieving">Retrieving elements from nil maps will not panic. The result is a zero element value.</a>
	</li>
	<li>
		<a class="index" href="#nil-map-element--deletion">Deleting an entry from a nil map will not panic. It is a no-op.</a>
	</li>
	<li>
		<a class="index" href="#append-slice-elements">The result slice of an <code>append</code> function call may share some elements with the original slice, or not.</a>
	</li>
	<li>
		<a class="index" href="#subslice">The length of a subslice may be larger than the base slice the subslice derives from.</a>
	</li>
	<li>
		<a class="index" href="#derive-from-nil-slice">Deriving a subslice from a nil slice is ok if all the indexes used in the subslice expression are zero. The result subslice is also a nil slice.</a>
	</li>
	<li>
		<a class="index" href="#range-over-nil-map-and-slice">Ranging over a nil maps or a nil slices is ok, it is a no-op.</a>
	</li>
	<li>
		<a class="index" href="#range-over-nil-array-pointer">Range over a nil array pointer is ok if the second iteration variable is ignored or omitted.</a>
	</li>
	<li>
		<a class="index" href="#modify-slice-length-and-capacity-separately">The length and capacity of a slice can be modified separately.</a>
	</li>
	<li>
		<a class="index" href="#indexes-in-composite-literals">The indexes in slice and array composite literals must be constants and non-negative.</a>
	</li>
	<li>
		<a class="index" href="#constant-keys-in-composite-literals">The constant indexes or keys in slice/array/map composite literals can't be duplicate.</a>
	</li>
	<li>
		<a class="index" href="#array-slice-element-addressability">Elements of unaddressable arrays are also unaddressable, but elements of unaddressable slices are always addressable.</a>
	</li>
	<li>
		<a class="index" href="#array-slice-derivable">It is ok to derive subslices from unaddressable slices, but not ok from unaddressable arrays. It is ok to take addresses for elements of unaddressable slices, but not ok for elements of unaddressable arrays.</a>
	</li>
	<li>
		<a class="index" href="#nan-as-map-keys">Putting entries with <code>NaN</code> as keys to a map is like putting the entries in a black hole.</a>
	</li>
	<li>
		<a class="index" href="#capacity-of-slice-from-string">The capacity of the result slice of a conversion from a string to byte/rune slice may be larger than the length of the result slice.</a>
	</li>
	<li>
		<a class="index" href="#different-loops">For a slice <code>s</code>, the loop <code>for i = range s {...}</code> is not equivalent to the loop <code>for i = 0; i &lt; len(s); i++ {...}</code>.</a>
	</li>
	</ul>
</li>
<li>
	Function and method related details:
	<ul class="index">
	<li>
		<a class="index" href="#call-as-expression">A multi-result function call can't mix with other expressions when the call is used as the sources in an assignment or the arguments of another function call.</a>
	</li>
	<li>
		<a class="index" href="#compile-time-evaluated-calls">Some function calls are evaluated at compile time.</a>
	</li>
	<li>
		<a class="index" href="#method-as-function">Each method corresponds to an implicit function.</a>
	</li>
	</ul>
</li>
<li>
	Interface related details:
	<ul class="index">
	<li>
		<a class="index" href="#comparison-interfaces-may-panic">Comparing two interface values with the same dynamic incomparable type produces a panic.</a>
	</li>
	<li>
		<a class="index" href="#type-assertion-to-interface-type">Type assertions can be used to convert a value of an interface type to another interface type, even if the former interface type doesn't implement the latter one.</a>
	</li>
	<li>
		<a class="index" href="#failed-type-assertion-may-panic">Whether or not the second optional result of a failed type assertion is present will affect the behavior of the type assertion.</a>
	</li>
	<!--
	<li>
		<a class="index" href="#interface-comparison-complexity">For the standard Go compiler, the time complexity of comparing two equal interface values may be <code><i>O</i>(1)</code> or <code><i>O</i>(n)</code>.</a>
	</li>
	<li>
		<a class="index" href="#interface-copy-complexity">For the standard Go compiler, the time complexity of copying an interface value is <code><i>O</i>(1)</code>.</a>
	</li>
	-->
	<li>
		<a class="index" href="#errors-new-different-returns">Two <code>error</code> values returned by two <code>errors.New</code> calls with the same argument are not equal.</a>
	</li>
	</ul>
</li>
<li>
	Channel related details:
	<ul class="index">
	<li>
		<a class="index" href="#receive-only-channel-canot-be-closed">Receive-only channels can't be closed.</a>
	</li>
	<li>
		<a class="index" href="#send-to-closed-channel-is-non-blocking">Sending a value to a closed channel is viewed as a non-blocking operation, and this operation causes a panic.</a>
	</li>
	</ul>
</li>
<li>
	More type and value related details:
	<ul class="index">
	<li>
		<a class="index" href="#local-type-declaration">Types can be declared within function bodies.</a>
	</li>
	<li>
		<a class="index" href="#final-zero-size-field">For the standard compiler, zero-sized fields in a struct may be treated as one-byte-sized value.</a>
	</li>
	<li>
		<a class="index" href="#nan-inf">NaN != NaN, Inf == Inf.</a>
	</li>
	<li>
		<a class="index" href="#non-exported-names-from-different-packages">Non-exported method names and struct field names from different packages are viewed as different names.</a>
	</li>
	</ul>
</li>
<li>
	Miscellanies:
	<ul class="index">
	<li>
		<a class="index" href="#sometimes-parentheses-are-required">Parentheses are required in several rare scenarios to make code compile okay.</a>
	</li>
	<!--
	<li>
		<a class="index" href="#main-entry-function-absence">A program doesn't need a <code>main</code> entry function to run.</a>
	</li>
	-->
	<li>
		<a class="index" href="#stack-overflow-is-not-panic">Stack overflow is not panic.</a>
	</li>
	<li>
		<a class="index" href="#some-evaluation-order-are-compiler-dependent">Some expression evaluation orders in Go are compiler implementation dependent.</a>
	</li>

	</ul>
</li>
<li>
	Standard packages related:
	<ul class="index">
	<li>
		<a class="index" href="#reflect-deep-equal">The results of <code>reflect.DeepEqual(x, y)</code> and <code>x == y</code> may be different.</a>
	</li>
	<li>
		<a class="index" href="#reflect-value-bytes">The <code>reflect.Value.Bytes()</code> method returns a <code>[]byte</code> value, which element type, <code>byte</code>, might be not the same as the Go slice value represented by the receiver parameter.</a>
	</li>
	<li>
		<a class="index" href="#check-file-existent">We should use <code>os.IsNotExist(err)</code> instead of <code>err == os.ErrNotExist</code> to check whether or not a file exists.</a>
	</li>
	<li>
		<a class="index" href="#boolean-flag">The <code>flag</code> standard package treats boolean command flags differently than number and string flags.</a>
	</li>
	<li>
		<a class="index" href="#printf-positional-arguments"><code>[Sp|Fp|P]rintf</code> functions support positional arguments.</a>
	</li>
	</ul>
</li>
</ul>
</div>

<div class="summaries-items">

<a class="anchor" id="import-package-multiple-times"></a>
<h3>A package can be imported more than once in a source file.</h3>

<div>
<p>
A Go source file can imports the same package multiple times,
but the import names must be different.
These same-package imports reference the same package instance.
</p>

For example:
<pre class="line-numbers"><code class="language-go">package main

import "fmt"
import "io"
import inout "io"

func main() {
	fmt.Println(&inout.EOF == &io.EOF) // true
}
</code></pre>
</div>

<a class="anchor" id="force-import-path"></a>
<h3>The comment <code>// import "x.y.z/mypkg"</code> following <code>package mypkg</code> is meaningful for the standard Go compiler.</h3>

<div>
For example, when the source files importing this package are compiled by the standard Go compiler,
the import path of the following package must be <code>"x.y.z/mypkg"</code>.

<pre class="line-numbers"><code class="language-go">package mypkg // import "x.y.z/mypkg"
...
</code></pre>

<p>
However, since Go SDK 1.11, the restriction <a href="https://golang.org/cmd/go/#hdr-Import_path_checking">doesn't apply for modules based and vendored packages</a>.
</p>
</div>

<a class="anchor" id="default-branch-position"></a>
<h3>The <code>default</code> branch in <code>switch</code> and <code>select</code> blocks can be put before all <code>case</code> branches, after all <code>case</code> branches, or between <code>case</code> branches.</h3>

<div>
For example:

<pre class="line-numbers"><code class="language-go">	switch n := rand.Intn(3); n {
	case 0: fmt.Println("n == 0")
	case 1: fmt.Println("n == 1")
	default: fmt.Println("n == 2")
	}

	switch n := rand.Intn(3); n {
	default: fmt.Println("n == 2")
	case 0: fmt.Println("n == 0")
	case 1: fmt.Println("n == 1")
	}

	switch n := rand.Intn(3); n {
	case 0: fmt.Println("n == 0")
	default: fmt.Println("n == 2")
	case 1: fmt.Println("n == 1")
	}

	var x, y chan int

	select {
	case <-x:
	case y <- 1:
	default:
	}

	select {
	case <-x:
	default:
	case y <- 1:
	}

	select {
	default:
	case <-x:
	case y <- 1:
	}
</code></pre>

<p>
</p>

</div>

<a class="anchor" id="constant-case-expressions"></a>
<h3>The numeric constant case expressions in a <code>switch</code> block can't be duplicate, but boolean ones can.</h3>

<div>
For example, the following program fails to compile.

<pre class="line-numbers"><code class="language-go">package main

func main() {
	switch 123 {
	case 123:
	case 123: // error: duplicate case
	}
}
</code></pre>

But the following program compiles okay.

<pre class="line-numbers"><code class="language-go">package main

func main() {
	switch false {
	case false:
	case false:
	}
}
</code></pre>

<p>
For reasons, please read <a href="https://github.com/golang/go/issues/28357">this issue</a>.
The behavior is compiler dependent.
In fact, the standard Go compiler also doesn't allow duplicate string case expressions, but gccgo allows.
</p>
</div>

<a class="anchor" id="switch-expressions-are-typed"></a>
<h3>The switch expressions in <code>switch</code> block are always evaluated to typed values.</h3>

<div>
For example, the switch expression <code>123</code> in the following <code>switch</code> block
is viewed as a value of <code>int</code> instead of an untyped integer.
So the following program fails to compile.

<pre class="line-numbers"><code class="language-go">package main

func main() {
	switch 123 {
	case int64(123):  // error: mismatched types
	case uint32(789): // error: mismatched types
	}
}
</code></pre>

<p>
</p>
</div>

<a class="anchor" id="default-switch-expression-value"></a>
<h3>The default switch expression of a <code>switch</code> block is a typed value <code>true</code> of the predeclared type <code>bool</code>.</h3>

<div>
For example, the following program will print <code>true</code>.

<pre class="line-numbers"><code class="language-go">package main

import "fmt"

func main() {
	switch { // <=> switch true {
	case true:  fmt.Println("true")
	case false: fmt.Println("false")
	}
}
</code></pre>

<p>
</p>
</div>

<a class="anchor" id="open-brace-on-the-next-line"></a>
<h3>Sometimes, the open brace <code>{</code> of an explicit code block can be put on the next line.</h3>

<div>
For example:

<pre class="line-numbers"><code class="language-go">package main

func main() {
	var i = 0
Outer:
	for
	{ // okay on the next line
		switch
		{ // okay on the next line
		case i == 5:
			break Outer
		default:
			i++
		}
	}
}
</code></pre>

<p></p>

What result will the following program print? <code>true</code> or <code>false</code>?
The answer is <code>true</code>.
Please read <a href="line-break-rules.html">line break rules in Go</a> for reasons.

<pre class="line-numbers"><code class="language-go">package main

import "fmt"

func False() bool {
	return false
}

func main() {
	switch False()
	{
	case true:  fmt.Println("true")
	case false: fmt.Println("false")
	}
}
</code></pre>

<p>
</p>

</div>

<a class="anchor" id="some-case-branch-blocks-must-be-explicit"></a>
<h3>Some <code>case</code> branch blocks must be explicit.</h3>

<div>
For example, the following program fails to compile.

<pre class="line-numbers"><code class="language-go">func demo(n, m int) (r int) {
	switch n {
	case 123:
		if m > 0 {
			goto End
		}
		r++

		End: // syntax error: missing statement after label
	default:
		r = 1
	}
	return
}
</code></pre>

To make it compile okay, the <code>case</code> branch code block should be explicit:

<pre class="line-numbers"><code class="language-go">func demo(n, m int) (r int) {
	switch n {
	case 123: {
		if m > 0 {
			goto End
		}
		r++

		End:
	}
	default:
		r = 1
	}
	return
}
</code></pre>

Alternatively, we can let a semicolon follow the label <code>End:</code>:

<pre class="line-numbers"><code class="language-go">func demo(n, m int) (r int) {
	switch n {
	case 123:
		if m > 0 {
			goto End
		}
		r++

		End:;
	default:
		r = 1
	}
	return
}
</code></pre>

<p>
Please read <a href="line-break-rules.html">line break rules in Go</a> for reasons.
</p>

</div>

<a class="anchor" id="defer-modify-results"></a>
<h3>A nested deferred function calls can modify return result values of its innermost nesting function.</h3>

<div>
For example:

<pre class="line-numbers"><code class="language-go">package main

import "fmt"

func F() (r int) {
	defer func() {
		r = 789
	}()

	return 123 // <=> r = 123; return
}

func main() {
	fmt.Println(F()) // 789
}
</code></pre>

<p>
</p>
</div>

<a class="anchor" id="no-op-recover-calls"></a>
<h3>Some <code>recover</code> calls may be NoOps.</h3>

<p>
We should call the <code>recover</code> function at the right places.
Please read <a href="panic-and-recover-more.html">the right places to call the built-in <code>recover</code> function</a> for details.
</p>

<a class="anchor" id="os-exit-runtime-goexit"></a>
<h3>Exit a program with a <code>os.Exit</code> function call and exit a goroutine with a <code>runtime.Goexit</code> function call.</h3>

<!--
https://github.com/golang/go/issues/29226 a bug of goexit
-->

<div>
<p>
We can exit a program from any function by calling the <code>os.Exit</code> function.
An <code>os.Exit</code> function call takes an <code>int</code> code as
argument and returns the code to operating system.
</p>

An example:

<pre class="line-numbers"><code class="language-go">// exit-example.go
package main

import "os"
import "time"

func main() {
	go func() {
		time.Sleep(time.Second)
		os.Exit(1)
	}()
	select{}
}
</code></pre>

Run it:

<pre class="output"><code>$ go run a.go
exit status 1
$ echo $?
1
</code></pre>

<p>
</p>

<p>
We can make a goroutine exit by calling the <code>runtime.Goexit</code> function.
The <code>runtime.Goexit</code> function has no parameters.
</p>

In the following example, the <code>Java</code> word will not be printed.

<pre class="line-numbers"><code class="language-go">package main

import "fmt"
import "runtime"

func main() {
	c := make(chan int)
	go func() {
		defer func() {c <- 1}()
		defer fmt.Println("Go")
		func() {
			defer fmt.Println("C")
			runtime.Goexit()
		}()
		fmt.Println("Java")
	}()
	<-c
}
</code></pre>

<p>
</p>

</div>

<a class="anchor" id="some-operator-precedence"></a>
<h3>The precedence of the increment operator <code>++</code> and the decrement <code>--</code> is lower than the dereference operator <code>*</code> and the address-taken operator <code>&amp;</code>, which are lower than the property selection operator <code>.</code> in selectors.</h3>

<div>
For example:

<pre class="line-numbers"><code class="language-go">package main

import "fmt"

type T struct {
	x int
	y *int
}

func main() {
	var t T
	p := &t.x // <=> p := &(t.x)
	fmt.Printf("%T\n", p) // *int

	*p++ // <=> (*p)++
	*p-- // <=> (*p)--

	t.y = p
	a := *t.y // <=> *(t.y)
	fmt.Printf("%T\n", a) // int
}
</code></pre>

<p>
</p>
</div>

<a class="anchor" id="type-deduction-in-bit-shift"></a>
<h3>The type deduction rule for the left untyped operand of a bit-shift operation depends on whether or not the right operand is a constant.</h3>

<div>


<pre class="line-numbers"><code class="language-go">package main

func main() {
}

const M  = 2
// Compiles okay. 1.0 is deduced as an int value.
var _ = 1.0 << M

var N = 2
// Fails to compile. 1.0 is deduced as a float64 value.
var _ = 1.0 << N
</code></pre>

<p>
Please read <a href="operators.html#bitwise-shift-left-operand-type-deduction">this article</a> for reasons.
</p>
</div>

<a class="anchor" id="conversion-of-pointers-with-different-underlying-types"></a>
<h3>Values of two pointer types with different underlying types can be converted to each other if the base types of their underlying types share the same underlying type.</h3>

<div>

An example:

<pre class="line-numbers"><code class="language-go">package main

type MyInt int64
type Ta    *int64
type Tb    *MyInt

func main() {
	var a Ta
	var b Tb

	// Direct conversion is not allowed.
	//a = Ta(b) // error

	// But indirect conversion is possible.
	y := (*MyInt)(b)
	x := (*int64)(y)
	a = x           // <=> the next line
	a = (*int64)(y) // <=> the next line
	a = (*int64)((*MyInt)(b))
	_ = a
}
</code></pre>

<p>
</p>
</div>

<a class="anchor" id="addresses-of-zeor-sized-values"></a>
<h3>Addresses of different zero-sized values may be equal, or not.</h3>
<!--
https://github.com/golang/go/issues/12726
-->

<div>
Whether or not the addresses of two zero-sized values are equal
is compiler and compiler version dependent.

<pre class="line-numbers"><code class="language-go">package main

import "fmt"

func main() {
	a := struct{}{}
	b := struct{}{}
	x := struct{}{}
	y := struct{}{}
	m := [10]struct{}{}
	n := [10]struct{}{}
	o := [10]struct{}{}
	p := [10]struct{}{}

	fmt.Println(&x, &y, &o, &p)

	// For the standard Go compiler (1.13),
	// x, y, o and p escape to heap, but
	// a, b, m and n are allocated on stack.

	fmt.Println(&a == &b) // false
	fmt.Println(&x == &y) // true
	fmt.Println(&a == &x) // false

	fmt.Println(&m == &n) // false
	fmt.Println(&o == &p) // true
	fmt.Println(&n == &p) // false
}
</code></pre>

<p>
The outputs indicated in the above code are for the standard Go compiler 1.13.
</p>
</div>

<a class="anchor" id="self-based-pointer-type"></a>
<h3>The base type of a pointer type may be the pointer type itself.</h3>

<div>

An example:

<pre class="line-numbers"><code class="language-go">package main

func main() {
	type P *P
	var p P
	p = &p
	p = **************p
}
</code></pre>

<p>
</p>

Similarly,
<ul>
<li>
	the element type of a slice type can be the slice type itself,
</li>
<li>
	the element type of a map type can be the map type itself,
</li>
<li>
	the element type of a channel type can be the channel type itself,
</li>
<li>
	and the argument and result types of a function type can be the function type itself.
</li>
</ul>

<pre class="line-numbers"><code class="language-go">package main

func main() {
	type S []S
	type M map[string]M
	type C chan C
	type F func(F) F

	s := S{0:nil}
	s[0] = s
	m := M{"Go": nil}
	m["Go"] = m
	c := make(C, 3)
	c <- c; c <- c; c <- c
	var f F
	f = func(F)F {return f}

	_ = s[0][0][0][0][0][0][0][0]
	_ = m["Go"]["Go"]["Go"]["Go"]
	<-<-<-c
	f(f(f(f(f))))
}
</code></pre>

<p>
</p>

</div>

<a class="anchor" id="pointer-selector-shorthands"></a>
<h3>A detail about selector shorthands.</h3>

<div>

<p>
For a pointer value, which type is either defined or not,
if the base type of its (pointer) type is a struct type,
then we can select the fields of the struct value
referenced by the pointer value through the pointer value.
However, if the type of the pointer value is a defined type,
then we can't select the methods of the struct value
referenced by the pointer value through the pointer value.
</p>

<pre class="line-numbers"><code class="language-go">package main

type T struct {
	x int
}
func (T) m(){} // T has one method.

type P *T  // a defined one-level pointer type.
type PP *P // a defined two-level pointer type.

func main() {
	var t T
	var tp = &t
	var tpp = &tp
	var p P = tp
	var pp PP = &p
	tp.x = 12  // okay
	p.x = 34   // okay
	pp.x = 56  // error: type PP has no field or method x
	tpp.x = 78 // error: type **T has no field or method x

	tp.m()  // okay. Type *T also has a "m" method.
	p.m()   // error: type P has no field or method m
	pp.m()  // error: type PP has no field or method m
	tpp.m() // error: type **T has no field or method m
}
</code></pre>
<p>
</p>
</div>

<a class="anchor" id="composite-literal-simplification"></a>
<h3>Sometimes, nested composite literals can be simplified.</h3>

<p>
Please read <a href="container.html#composite-literal-simplification">nested composite literals can be simplified</a> for details.
</p>

<a class="anchor" id="use-pointer-as-array"></a>
<h3>In some scenarios, it is ok to use array pointers as arrays.</h3>

<p>
Please read <a href="container.html#use-pointer-as-array">use array pointers as arrays</a> for details.
</p>

<a class="anchor" id="nil-map-element-retrieving"></a>
<h3>Retrieving elements from nil maps will not panic. The result is a zero element value.</h3>

<div>

For example, the <code>Foo1</code> and the <code>Foo2</code> functions are equivalent,
but the function <code>Foo2</code> is much tidier than the function <code>Foo1</code>.

<pre class="line-numbers"><code class="language-go">func Foo1(m map[string]int) int {
	if m != nil {
		return m["foo"]
	}
	return 0
}

func Foo2(m map[string]int) int {
	return m["foo"]
}
</code></pre>

<p>
</p>
</div>

<a class="anchor" id="nil-map-element--deletion"></a>
<h3>Deleting an entry from a nil map will not panic. It is a no-op.</h3>

<div>

For example, the following program will not panic.

<pre class="line-numbers"><code class="language-go">package main

func main() {
	var m map[string]int // nil
	delete(m, "foo")
}
</code></pre>

<p>
</p>
</div>

<a class="anchor" id="append-slice-elements"></a>
<h3>The result slice of an <code>append</code> function call may share some elements with the original slice, or not.</h3>

<p>
Please read <a href="container.html#element-addition-deletion">append and delete container elements</a> for details.
</p>

<a class="anchor" id="subslice"></a>
<h3>The length of a subslice may be larger than the base slice the subslice derives from.</h3>

<div>

For example,

<pre class="line-numbers"><code class="language-go">package main

import "fmt"

func main() {
	s := make([]int, 3, 9)
	fmt.Println(len(s)) // 3
	s2 := s[2:7]
	fmt.Println(len(s2)) // 5
}
</code></pre>

<p>
Please read <a href="container.html#subslice">derive slices from arrays and slices</a> for details.
</p>
</div>

<a class="anchor" id="derive-from-nil-slice"></a>
<h3>Deriving a subslice from a nil slice is ok if all the indexes used in the subslice expression are zero. The result subslice is also a nil slice.</h3>

<div>

For example, the following program will not panic at run time.

<pre class="line-numbers"><code class="language-go">package main

import "fmt"

func main() {
	var x []int // nil
	a := x[:]
	b := x[0:0]
	c := x[:0:0]
	// Print three "true".
	fmt.Println(a == nil, b == nil, c == nil)
}
</code></pre>

<p>
Please read <a href="container.html#subslice">derive slices from arrays and slices</a> for details.
</p>
</div>

<a class="anchor" id="range-over-nil-map-and-slice"></a>
<h3>Ranging over a nil maps or a nil slices is ok, it is a no-op.</h3>

<div>

For example, the following program compiles okay.

<pre class="line-numbers"><code class="language-go">package main

func main() {
	var s []int // nil
	for range s {
	}

	var m map[string]int // nil
	for range m {
	}
}
</code></pre>

<p>
</p>
</div>

<a class="anchor" id="range-over-nil-array-pointer"></a>
<h3>Range over a nil array pointer is ok if the second iteration variable is ignored or omitted.</h3>

<div>

For example, the following program will print <code>01234</code>.

<pre class="line-numbers"><code class="language-go">package main

import "fmt"

func main() {
	var a *[5]int // nil
	for i, _ := range a {
		fmt.Print(i)
	}
}
</code></pre>

<p>
</p>
</div>

<a class="anchor" id="modify-slice-length-and-capacity-separately"></a>
<h3>The length and capacity of a slice can be modified separately.</h3>

<p>
We can modify the length and capacity of a slice separately through the reflection way.
Please read <a href="container.html#modify-slice-length-and-capacity">modify the length and capacity properties of a slice individually</a> for details.
</p>

<a class="anchor" id="indexes-in-composite-literals"></a>
<h3>The indexes in slice and array composite literals must be constants and non-negative.</h3>

<div>
For example, the following code fails to compile.

<pre class="line-numbers"><code class="language-go">var k = 1
// error: index must be non-negative integer constant
var x = [2]int{k: 1}
// error: index must be non-negative integer constant
var y = []int{k: 1}
</code></pre>

<p>
Note, the keys in map composite literals are not required to be constants.
</p>
</div>

<a class="anchor" id="constant-keys-in-composite-literals"></a>
<h3>The constant indexes or keys in slice/array/map composite literals can't be duplicate.</h3>

<div>
For example, the following code fails to compile.

<pre class="line-numbers"><code class="language-go">// error: duplicate index in array literal: 1
var a = []bool{0: false, 1: true, 1: true}
// error: duplicate index in array literal: 0
var b = [...]string{0: "foo", 1: "bar", 0: "foo"}
// error: duplicate key "foo" in map literal
var c = map[string]int{"foo": 1, "foo": 2}
</code></pre>

<p>
This feature can be used to <a href="tips.html#assert-at-compile-time">assert some conditions at compile time</a>.
</p>
</div>

<a class="anchor" id="array-slice-element-addressability"></a>
<h3>Elements of unaddressable arrays are also unaddressable, but elements of unaddressable slices are always addressable.</h3>

<div>
<p>
The reason is the elements of an array value and the array will be stored
in the same memory block when the array is stored in memory.
But <a href="unofficial-faq.html#slice-elements-always-addressable">the
situation is different for slices</a>.
</p>

An example:

<pre class="line-numbers"><code class="language-go">package main

func main() {
	// Container composite literals are unaddressable.

	// It is ok to take slice literal element addresses.
	_ = &[]int{1}[0] // ok
	// Cannot take addresses of array literal elements.
	_ = &[5]int{}[0] // error

	// It is ok to modify slice literal elements.
	[]int{1,2,3}[1] = 9  // ok
	// Cannot modify array literal elements.
	[3]int{1,2,3}[1] = 9 // error
}
</code></pre>

<p>
</p>
</div>

<a class="anchor" id="array-slice-derivable"></a>
<h3>
It is ok to derive subslices from unaddressable slices, but not ok from unaddressable arrays.
</h3>

<div>
<p>
The reason is the same as the last detail.
</p>

An example:
<pre class="line-numbers"><code class="language-go">package main

func main() {
	// Map elements are unaddressable in Go.

	// The following lines compile okay. Deriving
	// slices from unaddressable slices is allowed.
	_ = []int{6, 7, 8, 9}[1:3]
	var ms = map[string][]int{"abc": {0, 1, 2, 3}}
	_ = ms["abc"][1:3]

	// The following lines fail to compile. Deriving
	// slices from unaddressable arrays is not allowed.
	/*
	_ = [...]int{6, 7, 8, 9}[1:3] // error
	var ma = map[string][4]int{"abc": {0, 1, 2, 3}}
	_ = ma["abc"][1:3]  // error
	*/
}
</code></pre>
<p>
</p>
</div>

<a class="anchor" id="nan-as-map-keys"></a>
<h3>Putting entries with <code>NaN</code> as keys to a map is like putting the entries in a black hole.</h3>

<div>
This reason is <code>NaN != NaN</code>, which is another detail will be described <a href="#nan-inf">below</a>.
Before Go 1.12, the elements with <code>NaN</code> as keys can only be found out in a <code>for-range</code> loop,
Since Go 1.12, the elements with <code>NaN</code> as keys can also be printed out by
<code>fmt.Print</code> alike functions.

<pre class="line-numbers"><code class="language-go">package main

import "fmt"
import "math"

func main() {
	var a = math.NaN()
	fmt.Println(a) // NaN

	var m = map[float64]int{}
	m[a] = 123
	v, present := m[a]
	fmt.Println(v, present) // 0 false
	m[a] = 789
	v, present = m[a]
	fmt.Println(v, present) // 0 false

	fmt.Println(m) // map[NaN:789 NaN:123]
	delete(m, a)   // no-op
	fmt.Println(m) // map[NaN:789 NaN:123]

	for k, v := range m {
		fmt.Println(k, v)
	}
	// the above loop outputs:
	// NaN 123
	// NaN 789
}
</code></pre>

<p>
Please note, before Go 1.12, the two <code>fmt.Println(m)</code>
calls both printed <code>map[NaN:&lt;nil&gt; NaN:&lt;nil&gt;]</code>.
</p>
</div>

<a class="anchor" id="capacity-of-slice-from-string"></a>
<h3>The capacity of the result slice of a conversion from a string to byte/rune slice may be larger than the length of the result slice.</h3>

<div>
<p>
We should not assume the length and the capacity of the result slice are always equal.
</p>

In the following example, if the last <code>fmt.Println</code> line is removed,
the outputs of the two lines before it print the same value <code>32</code>,
otherwise, one print <code>32</code> and one print <code>8</code>
(for the standard Go compiler 1.13).

<pre class="line-numbers"><code class="language-go">package main

import "fmt"

func main() {
	s := "a"
	x := []byte(s)              // len(s) == 1
	fmt.Println(cap([]byte(s))) // 32
	fmt.Println(cap(x))         // 8
	fmt.Println(x)
}
</code></pre>

<p>
<a href="https://github.com/go101/go101/wiki/The-capacity-of-the-result-byte-%28or-rune%29-slice-of-a-conversion-from-a-string-is-undefined">Some buggy code will be written</a> if we assume the length and the capacity of the result slice are always equal.
</p>
</div>

<a class="anchor" id="different-loops"></a>
<h3>For a slice <code>s</code>, the loop <code>for i = range s {...}</code> is not equivalent to the loop <code>for i = 0; i &lt; len(s); i++ {...}</code>.</h3>

<div>
The respective final values of the iteration variable <code>i</code>
may be different for the two loops.

<pre class="line-numbers"><code class="language-go">package main

import "fmt"

var i int

func fa(s []int, n int) int {
	i = n
	for i = 0; i < len(s); i++ {}
	return i
}

func fb(s []int, n int) int {
	i = n
	for i = range s {}
	return i
}

func main() {
	s := []int{2, 3, 5, 7, 11, 13}
	fmt.Println(fa(s, -1), fb(s, -1)) // 6 5
	s = nil
	fmt.Println(fa(s, -1), fb(s, -1)) // 0 -1
}
</code></pre>

<p>
</p>
</div>

<a class="anchor" id="call-as-expression"></a>
<h3>A multi-result function call can't mix with other expressions when the call is used as the sources in an assignment or the arguments of another function call.</h3>

<p>
Please read <a href="function.html#call-as-expression">use function calls as expressions</a> for details.
</p>

<a class="anchor" id="compile-time-evaluated-calls"></a>
<h3>Some function calls are evaluated at compile time.</h3>

<p>
Please read <a href="function.html#compile-time-evaluated-calls">some function calls are evaluated at compile time</a> for details.
</p>

<a class="anchor" id="method-as-function"></a>
<h3>Each method corresponds to an implicit function.</h3>

<p>
Please read <a href="method.html#method-as-function">each Method Corresponds to an Implicit Function</a> for details.
</p>

<a class="anchor" id="comparison-interfaces-may-panic"></a>
<h3>Comparing two interface values with the same dynamic incomparable type produces a panic.</h3>

<div>
For example:

<pre class="line-numbers"><code class="language-go">package main

func main() {
	var x interface{} = []int{}
	_ = x == x // panic
}
</code></pre>

<p>
</p>
</div>

<a class="anchor" id="type-assertion-to-interface-type"></a>
<h3>Type assertions can be used to convert a value of an interface type to another interface type, even if the former interface type doesn't implement the latter one.</h3>

<div>
For example:

<pre class="line-numbers"><code class="language-go">package main

type Foo interface {
	foo()
}

type T int
func (T) foo() {}

func main() {
	var x interface{} = T(123)
	// The following two lines fails to compile, for the
	// same reason: interface{} does not implement Foo.
	/*
	var _ Foo = x   // error
	var _ = Foo(x)  // error
	*/
	// But the following line compiles and runs okay.
	var _ = x.(Foo) // okay
}
</code></pre>

<p>
</p>
</div>

<a class="anchor" id="failed-type-assertion-may-panic"></a>
<h3>Whether or not the second optional result of a type assertion is present will affect the behavior of the type assertion.</h3>

<div>
If the second optional result presents in a failed type assertion, the type assertion will not produce a panic.
Otherwise, a panic will occur.
For example:

<pre class="line-numbers"><code class="language-go">package main

func main() {
	var x interface{} = true

	// Assertion fails, but doesn't cause a panic.
	_, _ = x.(int)

	// Assertion fails, which causes a panic.
	_ = x.(int)
}
</code></pre>

<p>
</p>
</div>



<!--
<a class="anchor" id="interface-comparison-complexity"></a>
<h3>For the standard Go compiler, the time complexity of comparing two equal interface values may be <code><i>O</i>(1)</code> or <code><i>O</i>(n)</code>.</h3>

<div>
The time complexity depends on whether or not the direct parts
of the two equal interfaces both reference the undrelying value.
Please read the article <a href="value-part.html#interface-structure">value parts</a> for detail.

<pre class="line-numbers"><code class="language-go">package main

import "fmt"
import "time"

func main() {
	bigarr := [1 << 20]int{}

	type I interface{}

	// i0, i1 and i2 are three equal interfaces.
	var i0 I = bigarr // the dynamic value of i0 is a copy of bigarr.
	var i1 I = bigarr // the dynamic value of i1 is also a copy of bigarr.
	                  // Note, the dynamic values of i0 and i1 are
	                  // two different copies of bigarr.
	var i2 I = i1 // i2 shares the same dynamic value copy with i1.

	startTime := time.Now()
	_ = i0 == i1
	duration := time.Since(startTime)
	fmt.Println("duration for (i0 == i1):", duration)

	startTime = time.Now()
	_ = i1 == i2
	duration = time.Since(startTime)
	fmt.Println("duration for (i1 == i2):", duration)
}
</code></pre>

The output:
<pre class="output"><code>duration for (i0 == i1): 1.381337ms
duration for (i1 == i2): 609ns
</code></pre>
<p>
1ms is 1000000ns!
</p>
</div>

<a class="anchor" id="interface-copy-complexity"></a>
<h3>About the time complexity of copying a non-nil interface value.</h3>

<p>
The <a href="https://golang.org/doc/faq#pass_by_value">official Go FAQ</a>
says <b><i>copying an interface value makes a copy of the thing stored in the interface value.</i></b>.
The article <a href="interface.html#boxing">interfaces in Go</a> mentions that,
for the standard Go compiler, the time complexity of copying an interface value
is <code><i>O</i>(1)</code>.
But the sizes of different dynamic values stored in interface values may
be different, why isn't the complexity <code><i>O</i>(n)</code>?
</p>

<p>
The reason is the dynamic values of interface values are all inmutable,
so the standard Go compiler makes an optimization here.
As the article <a href="value-part.html#interface-structure">value parts</a>
has explained, an non-nil interface value has an underlying part and
the direct part of the interface value stores a pointer which
references the underlying part. When the interface value is copied,
only its direct part is copied. For the standard Go compiler,
the sizes of the direct parts of all interface values are the same.
</p>
-->

<a class="anchor" id="errors-new-different-returns"></a>
<h3>Two <code>error</code> values returned by two <code>errors.New</code> calls with the same argument are not equal.</h3>

<div>
The reason is the <code>errors.New</code> function will copy the input string argument
and use a pointer to the copied string as the dynamic value of the returned <code>error</code> value.
Two different calls will produce two different pointers.

<pre class="line-numbers"><code class="language-go">package main

import "fmt"
import "errors"

func main() {
	notfound := "not found"
	a, b := errors.New(notfound), errors.New(notfound)
	fmt.Println(a == b) // false
}
</code></pre>

<p>
</p>
</div>

<a class="anchor" id="receive-only-channel-canot-be-closed"></a>
<h3>Receive-only channels can't be closed.</h3>

<div>
For example, the following code fails to compile.

<pre class="line-numbers"><code class="language-go">package main

func main() {
}

func foo(c <-chan int) {
	close(c) // error: cannot close receive-only channel
}
</code></pre>

<p>
</p>
</div>

<a class="anchor" id="send-to-closed-channel-is-non-blocking"></a>
<h3>Sending a value to a closed channel is viewed as a non-blocking operation, and this operation causes a panic.</h3>

<div>
For example, in the following program, when the second <code>case</code> branch gets selected, it will produce a panic at run time.

<pre class="line-numbers"><code class="language-go">package main

func main() {
	var c = make(chan bool)
	close(c)
	select {
	case <-c:
	case c <- true: // panic: send on closed channel
	default:
	}
}
</code></pre>

<p>
</p>
</div>

<a class="anchor" id="local-type-declaration"></a>
<h3>Types can be declared within function bodies.</h3>

<div>
Types can be declared in function bodies. For example,

<pre class="line-numbers"><code class="language-go">package main

func main() {
	type T struct{}
	type S = []int
}
</code></pre>
<p>
</p>
</div>

<a class="anchor" id="final-zero-size-field"></a>
<h3>For the standard compiler, zero-sized fields in a struct may be treated as one-byte-sized value.</h3>

<p>
Please read <a href="unofficial-faq.html#final-zero-size-field">this FAQ item</a> for details.
</p>

<a class="anchor" id="nan-inf"></a>
<h3>NaN != NaN, Inf == Inf.</h3>

<div>
This follows IEEE-754 standard and is consistent with most other programming languages:
<pre class="line-numbers"><code class="language-go">package main

import "fmt"
import "math"

func main() {
	var a = math.Sqrt(-1.0)
	fmt.Println(a)      // NaN
	fmt.Println(a == a) // false

	var x = 0.0
	var y = 1.0 / x
	var z = 2.0 * y
	fmt.Println(y, z, y == z) // +Inf +Inf true
}
</code></pre>
<p>
</p>
</div>

<a class="anchor" id="non-exported-names-from-different-packages"></a>
<h3>Non-exported method names and struct field names from different packages are viewed as different names.</h3>

<div>
For example, if the following types are declared in package <code>foo</code>:

<pre class="line-numbers"><code class="language-go">package foo

type I = interface {
	about() string
}

type S struct {
	a string
}

func (s S) about() string {
	return s.a
}
</code></pre>

and the following types are declared in package <code>bar</code>:

<pre class="line-numbers"><code class="language-go">package bar

type I = interface {
	about() string
}

type S struct {
	a string
}

func (s S) about() string {
	return s.a
}
</code></pre>

then,
<ul>
<li>
	values of the two respective types <code>S</code> from the two packages
	can't be converted to each other.
</li>
<li>
	the two respective interface types <code>S</code> from the two packages
	denote two distinct method sets.
</li>
<li>
	type <code>foo.S</code> doesn't implement the interface type <code>bar.I</code>.
</li>
<li>
	type <code>bar.S</code> doesn't implement the interface type <code>foo.I</code>.
</li>
</ul>

<pre class="line-numbers"><code class="language-go">package main

import "包2/foo"
import "包2/bar"

func main() {
	var x foo.S
	var y bar.S
	var _ foo.I = x
	var _ bar.I = y

	// The following lines fail to compile.
	x = foo.S(y)
	y = bar.S(x)
	var _ foo.I = y
	var _ bar.I = x
}
</code></pre>

</div>

<a class="anchor" id="sometimes-parentheses-are-required"></a>
<h3>Parentheses are required in several rare scenarios to make code compile okay.</h3>

<div>
For example:

<pre class="line-numbers"><code class="language-go">package main

type T struct{x, y int}

func main() {
	// Each of the following three lines makes code
	// fail to compile. Some "{}"s confuse compilers.
	/*
	if T{} == T{123, 789} {}
	if T{} == (T{123, 789}) {}
	if (T{}) == T{123, 789} {}
	var _ = func()(nil) // nil is viewed as a type
	*/

	// We must add parentheses like the following
	// two lines to make code compile okay.
	if (T{} == T{123, 789}) {}
	if (T{}) == (T{123, 789}) {}
	var _ = (func())(nil) // nil is viewed as a value
}
</code></pre>

<p>
</p>
</div>

<!--
<a class="anchor" id="main-entry-function-absence"></a>
<h3>A program doesn't need a <code>main</code> entry function to run.</h3>

<div>
The following program <a href="https://github.com/golang/go/issues/21256">compiles okay before Go 1.11</a>,
for the standard Go compiler.
But since Go 1.11, it fails to compile.

<pre class="line-numbers"><code class="language-go">package main

import (
    "fmt"
    "time"
)

func init() {
	for {
		time.Sleep(time.Second)
		fmt.Println("hi")
	}
}

var main int
</code></pre>

<p>
</p>
</div>
-->

<a class="anchor" id="stack-overflow-is-not-panic"></a>
<h3>Stack overflow is not panic.</h3>

<div>

Stack overflow in Go is fatal error. Once a stack overflow happens, program will crash with no recovery ways.

<pre class="line-numbers"><code class="language-go">package main

func f() {
	f()
}

func main() {
	defer func() {
		recover() // helpless to avoid program crashing
	}()
	f()
}
</code></pre>

the running result:

<pre class="output"><code>runtime: goroutine stack exceeds 1000000000-byte limit
fatal error: stack overflow

runtime stack:
...
</code></pre>

<p>
</p>
</div>

<a class="anchor" id="some-evaluation-order-are-compiler-dependent"></a>
<h3>Some expression evaluation orders in Go are compiler implementation dependent.</h3>

<p>
Please read <a href="evaluation-orders.html">expression evaluation orders in Go</a> for details.
</p>

<a class="anchor" id="reflect-deep-equal"></a>
<h3>The results of <code>reflect.DeepEqual(x, y)</code> and <code>x == y</code> may be different.</h3>

<div>
<p>
The function call <code>reflect.DeepEqual(x, y)</code> will always return
<code>false</code> if the types of its two arguments are different,
whereas <code>x == y</code> may return <code>true</code> even if
the types of the two operands are different.
</p>

<p>
The second difference is a <code>DeepEqual</code> call with
two pointer argument values of the same type returns whether or not
the two respective values referenced by the two pointers are deep equal.
So the call might return <code>true</code> even if the two pointers are not equal.
</p>

<p>
The third difference is the result of a <code>DeepEqual</code> call may be not
correct if the compared two arguments are in the same cyclic reference chain.
</p>

<p>
The fourth difference is, the function call
<code>reflect.DeepEqual(x, y)</code> is not expected to panic generally,
whereas <code>x == y</code> will panic if the two operands are both
interface values and their dynamic types are identical and incomparable.
</p>

An example showing these differences:

<pre class="line-numbers"><code class="language-go">package main

import "fmt"
import "reflect"

func main() {
	type Book struct {page int}
	x := struct {page int}{123}
	y := Book{123}
	fmt.Println(reflect.DeepEqual(x, y)) // false
	fmt.Println(x == y)                  // true

	z := Book{123}
	fmt.Println(reflect.DeepEqual(&z, &y)) // true
	fmt.Println(&z == &y)                  // false

	type T struct{p *T}
	t := &T{&T{nil}}
	t.p.p = t // form a cyclic reference chain.
	fmt.Println(reflect.DeepEqual(t, t.p)) // true
	fmt.Println(t == t.p)                  // false

	var f1, f2 func() = nil, func(){}
	fmt.Println(reflect.DeepEqual(f1, f1)) // true
	fmt.Println(reflect.DeepEqual(f2, f2)) // false

	var a, b interface{} = []int{1, 2}, []int{1, 2}
	fmt.Println(reflect.DeepEqual(a, b)) // true
	fmt.Println(a == b)                  // panic
}
</code></pre>

<p>
Note, if the two arguments of a <code>DeepEqual</code> call are both function values,
then the call returns <code>true</code> only if the two function arguments are both nil and their types are identical.
</p>

<p>
So, to compare values of a type by using <code>reflect.DeepEqual</code>,
a programmer needs to understand the structure definition of the type well.
</p>
</div>

<a class="anchor" id="reflect-value-bytes"></a>
<h3>The <code>reflect.Value.Bytes()</code> method returns a <code>[]byte</code> value, which element type, <code>byte</code>, might be not the same as the Go slice value represented by the receiver parameter.</h3>

<div>
<p>
Assume the underlying type of a defined type <code>MyByte</code> is the
predeclared type <code>byte</code>, we know that Go type system forbids
the conversions between <code>[]MyByte</code> and <code>[]byte</code> values.
However, it looks the implementation of the method <code>Bytes</code> of the
<code>reflect.Value</code> type partially violates this restriction unintentionally,
by allowing converting a <code>[]MyByte</code> value to <code>[]byte</code>.
</p>

Example:

<pre class="line-numbers"><code class="language-go">package main

import "bytes"
import "fmt"
import "reflect"

type MyByte byte

func main() {
	var mybs = []MyByte{'a', 'b', 'c'}
	var bs []byte

	// bs = []byte(mybs) // this line fails to compile

	v := reflect.ValueOf(mybs)
	bs = v.Bytes() // okay. Violating Go type system.
	fmt.Println(bytes.HasPrefix(bs, []byte{'a', 'b'})) // true

	bs[1], bs[2] = 'r', 't'
	fmt.Printf("%s \n", mybs) // art
}
</code></pre>

<p>
But it looks the violation is not harmful.
On the contrary, it makes some benefits.
For example, with this violation, we can use the functions in the
<code>bytes</code> standard package for the <code>[]MyByte</code> values.
</p>

<p>
Note, the <code>reflect.Value.Bytes()</code> method <a href="https://github.com/golang/go/issues/27727">might be removed later</a>.
</p>

</div>

<a class="anchor" id="check-file-existent"></a>
<h3>We should use <code>os.IsNotExist(err)</code> instead of <code>err == os.ErrNotExist</code> to check whether or not a file exists.</h3>

<div>

Using <code>err == os.ErrNotExist</code> may miss errors.

<pre class="line-numbers"><code class="language-go">package main

import (
	"fmt"
	"os"
)

func main() {
	_, err := os.Stat("a-nonexistent-file.abcxyz")
	fmt.Println(os.IsNotExist(err))    // true
	fmt.Println(err == os.ErrNotExist) // false
}
</code></pre>

<p>
</p>

For projects only support Go 1.13+, <code>errors.Is(err, os.ErrNotExist)</code> is more recommended
to be used to check whether or not a file exists.

<pre class="line-numbers"><code class="language-go">package main

import (
	"errors"
	"fmt"
	"os"
)

func main() {
	_, err := os.Stat("a-nonexistent-file.abcxyz")
	fmt.Println(errors.Is(err, os.ErrNotExist)) // true
}
</code></pre>

<p>
</p>
</div>

<a class="anchor" id="boolean-flag"></a>
<h3>The <code>flag</code> standard package treats boolean command flags differently than integer and string flags.</h3>

<div>
There are three forms to pass flag options.
<ol>
<li>
	<code>-flag</code>, for boolean flags only.
</li>
<li>
	<code>-flag=x</code>, for any flag.
</li>
<li>
	<code>-flag x</code>, for non-boolean flags only.
</li>
</ol>

<p>
And please note that, a boolean flag with the first form
is viewed as the last flag, all items following it are viewed as arguments.
</p>

<pre class="line-numbers"><code class="language-go">package main

import "fmt"
import "flag"

var b = flag.Bool("b", true, "a boolean flag")
var i = flag.Int("i", 123, "an integer flag")
var s = flag.String("s", "hi", "a string flag")

func main() {
	flag.Parse()
	fmt.Print("b=", *b, ", i=", *i, ", s=", *s, "\n")
	fmt.Println("arguments:", flag.Args())
}
</code></pre>

<p>
</p>

If we run the following program with the below shown flags and arguments

<pre class="output"><code>./exampleProgram -b false -i 789 -s bye arg0 arg1
</code></pre>

the output will be

<pre class="output"><code>b=true, i=123, s=hi
arguments: [false -i 789 -s bye arg0 arg1]
</code></pre>

<p>
This output is obviously not what we expect.
</p>

We should pass the flags and arguments like

<pre class="output"><code>./exampleProgram -b=false -i 789 -s bye arg0 arg1
</code></pre>

or

<pre class="output"><code>./exampleProgram -i 789 -s bye -b arg0 arg1
</code></pre>

to get the output we expect:

<pre class="output"><code>b=true, i=789, s=bye
arguments: [arg0 arg1]
</code></pre>

</div>

<a class="anchor" id="printf-positional-arguments"></a>
<h3><code>[Sp|Fp|P]rintf</code> functions support positional arguments.</h3>

<div>
The following program will print <code>coco</code>.

<pre class="line-numbers"><code class="language-go">package main

import "fmt"

func main() {
	// The next line prints: coco
	fmt.Printf("%[2]v%[1]v%[2]v%[1]v", "o", "c")
}
</code></pre>

<p>
</p>
</div>




</div> <!-- summaries-items -->

<!--
<a class="anchor" id="remove-spaces-in-template"></a>
<h3>Since Go 1.6, we can .</h3>

https://golang.org/doc/go1.6 : {{a -}} sss {{- b}}



The exported fields and methods of embedded non-exported fields
are still exported for the embedding struct type.


json:"name: empty" // doesn't work

syscall package docs show current O arch defaultly
  https://golang.org/pkg/syscall/?GOOS=linux&GOARCH=mips64le

two non-defined struct types embedding two type aliases which denote the same type are two different types.

non-exported field can't be set by reflection, but can be listed. Can read?

reflection created embedding type will not obtain meethods. still?

don't use == to compare two reflect.Value values, compare v1.Interface() and v2.Interface() instead (move to reflection article and tips)

don't use == compare two time.Time values, use time.EqualTo instead (move to tips)

https://golang.org/pkg/reflect/#pkg-note-BUG

https://golang.org/pkg/reflect/#Value.String
Print functions not always print the result of the String() method of a value.



size_t in go is int instead of uint, ..., good design. (to faq)

an untyped rune or int constant can be bound with a value which is larger than the max <code>rune</code> or <code>int</code> value in memory.

-128/-1 = -128


greedy goroutine https://github.com/golang/go/issues/10958
* It look some goroutines never get yielded, this make some other goroutines never get chances to run, why?
http://stackoverflow.com/questions/13107958/what-exactly-does-runtime-gosched-do

internal package

"go doc xyz" may show the docs of the first package named with "xyz"
https://github.com/golang/go/issues/24462
For example, "go doc rand" show docs of "math/rand" instead of "crypto/rand".


runtime.Caller/ Callers: depth onconsistencys

https://github.com/golang/go/issues/13890

https://github.com/golang/go/issues/24693

https://github.com/golang/go/issues/24721

https://github.com/golang/go/issues/20135

Try not to use multi-value assignments.
Reason 1: maybe bug. Reason 3: unspecified behaviours. 2: maybe inefficient.
https://github.com/golang/go/issues/23188#issuecomment-361482955
https://github.com/golang/go/issues/23017
https://github.com/golang/go/issues/22881
https://github.com/golang/go/issues/24448

https://github.com/golang/go/issues/24746

https://github.com/golang/go/issues/26463 maps do not shrink

Values of <code>expvar.Int</code> and <code>expvar.Float</code> need to be 64-bit aligned.

func main() {
	var a, b = 1.0, 0.0
	x, y := a/b, 0.0
	println(x, y) // +Inf +0.000000e+000
	println(x * y) // NaN
}

The String method of a reflect.Value value v returns the string form of the underlying value of v.
However, the functions in the fmt package try to print the string form of the underlying value of the underlying value of v,
if the underlying value of v is also a reflect.Value value.

	package main

	import (
		"fmt"
		"reflect"
	)

	func main() {
		var v reflect.Value
		fmt.Println(v.IsValid()) // false
		fmt.Println(v)           // <invalid reflect.Value>
		fmt.Println(v.String())  // <invalid Value>
		
		v = reflect.ValueOf(v)
		fmt.Println(v.IsValid()) // true
		fmt.Println(v)           // <invalid Value>
		fmt.Println(v.String())  // <reflect.Value Value>
		
		v = reflect.ValueOf(v)
		fmt.Println(v.IsValid()) // true
		fmt.Println(v)           // <reflect.Value Value>
		fmt.Println(v.String())  // <reflect.Value Value>
	}

io/ioutil since Go 1.11
 writer or writable values.
    The TempFile function now supports specifying where the random characters in the filename are placed.
    If the prefix argument includes a "*", the random string replaces the "*".
    For example, a prefix argument of "myname.*.bat" will result in a random filename such as "myname.123456.bat".
    If no "*" is included the old behavior is retained, and the random digits are appended to the end.

go links 101
   https://stackoverflow.com/questions/7044944/jquery-javascript-to-detect-os-without-a-plugin
   https://golang.org/pkg/syscall/ list all OS/arch pages

//godo/doc/builder
var windowsOnlyPackages = map[string]bool{
	"internal/syscall/windows":                     true,
	"internal/syscall/windows/registry":            true,
	"golang.org/x/exp/shiny/driver/internal/win32": true,
	"golang.org/x/exp/shiny/driver/windriver":      true,
	"golang.org/x/sys/windows":                     true,
	"golang.org/x/sys/windows/registry":            true,
}

go term(inoledgie)s 101

go contests 101 / summaries / snippets






since Go 1.12, map entry print orders are specified,
though iteration order is sitll unspecified.
If there are a large quantity of entires in a map,
then printing might consume much time.

1.13+: one more DeepEqual exception: https://go-review.googlesource.com/c/go/+/168438/3/src/reflect/deepequal.go

TrimSpace may return nil even if the input is not: https://github.com/golang/go/issues/31038

tight loops should be preemptible
https://github.com/golang/go/issues/10958


method value evaluation timing
* https://github.com/golang/go/issues/32Gosched021
* https://github.com/golang/go/issues/32035

https://github.com/golang/go/issues/22075

https://github.com/golang/go/issues/18531

https://github.com/golang/go/issues/23224

deferred calls will be called after runtime.Goexit 
but will not after os.Exit. Note, log.Fatal wraps os.Exit.
If a program does clean-up work in deferred calls, don't use os.Exit to terminate the program.

package main
import "C" // commentting out this line crashes this program
func main() {
  select{}
}

https://github.com/golang/go/issues/34684
syscall.Proc.Call and syscall.LazyProc.Call are not implemented in assembly, and, as such, this rule does not apply to them.

The print result of nil and blank slices are the same. (Similar to maps).
* history reason

In JSON marshal results, the map entries will be sorted by their keys, but the items in slices will not be sorted.

-->








